package com.gonsin.ta.logic.parse;

import com.gonsin.ta.logic.exceptions.TaException;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.InputStream;

@Slf4j
@Component
public class TaFileReader {


    @SneakyThrows
    public String readContent(String path, String file, String encoder) {
        log.info("echo params：{},{},{}",path,file,encoder);
        File filePath = new File(path + file);
        if(filePath.exists()){
            return FileUtils.readFileToString(filePath, encoder);
        }
//        filePath = ResourceUtils.getFile("classpath:" + path + file);
        File targetFile = new File(file);
//        Resource resource = new ClassPathResource(path + file);
//        FileUtils.copyInputStreamToFile(resource.getInputStream(), targetFile);
        InputStream inputStream = TaFileReader.class.getClassLoader().getResourceAsStream(path + file);
        FileUtils.copyInputStreamToFile(inputStream, targetFile);
        if(targetFile.exists()){
            String result = FileUtils.readFileToString(targetFile, encoder);
            targetFile.delete();
            return result;
        }
        throw new TaException("无法读取文件{}的内容",path + file);
    }
}
